package service.wx

import com.alibaba.fastjson.JSON

import org.slf4j.Logger
import org.slf4j.LoggerFactory

import com.github.kevinsawicki.http.HttpRequest

class WxApi {
	static Logger log = LoggerFactory.getLogger(WxApi.class)

	final static String urlApiHost = 'https://api.weixin.qq.com/'
	final static String urlPre = urlApiHost + 'cgi-bin/'

	private static Map doPost(String action, Map params){
		String accessToken = WxSignature.getAccessToken()
		String url = urlPre + action + '?access_token=' + accessToken

		def req = HttpRequest.post(url).send(JSON.toJSONString(params))
		String resultText = req.body()

		try {
			def objResult = JSON.parseObject(resultText)
			log.info(action + ' - ' + objResult)

			objResult
		}catch(ex) {
			log.error('error-when-parse-url-result - ' + resultText, ex)
			[errcode: -1, errmsg: ex.message]
		}
	}

	private static Map doGet(String action, Map params = null){
		String accessToken = WxSignature.getAccessToken()
		String url = urlPre + action + '?access_token=' + accessToken

		if(params != null){
			for(one in params){
				url += '&' + one.key + '=' + one.value
			}
		}

		String resultText = HttpRequest.get(url).body()
		try {
			def objResult = JSON.parseObject(resultText)
			log.info(action + ' - ' + objResult)

			objResult
		}catch(ex) {
			log.error('error-when-parse-url-result - ' + resultText, ex)
			[errcode: -1, errmsg: ex.message]
		}
	}

	public static String generateNonce(int len = 32){
		String base = 'abcdefghijklmnopqrstuvwxyz0123456789'
		int baseLen = base.size()

		def sb = new StringBuilder()
		def rand = new Random()

		for(int i = 0; i < len; i++){
			int begin = rand.nextInt(baseLen - 1)
			sb << base.substring(begin, begin + 1)
		}

		sb.toString()
	}

	static boolean isReqFromWx(String ua){
		return ua.contains('MicroMessenger')
	}

	// 创建菜单
	static Map createMenu(Map params){
		doPost('menu/create', params)
	}

	// 用户分组，创建
	static Map createGroup(String name){
		doPost('groups/create', [group: [name: name]])

		// return [group: [id: ***, name: name]]
	}

	// 用户分组，修改
	static Map updateGroup(int id, String name){
		doPost('groups/update', [group: [id: id, name: name]])

		// return errcode/errmsg
	}

	// 用户分组，查询
	static Map getGroups(){
		doGet('groups/get')

		// return [groups: [[id: ***, name: ***, count: ***]]]
	}

	// 查询用户所在分组
	static Map getUserGroupId(String openid){
		doPost('groups/getid', [openid: openid])

		// return [groupid: ***]
	}

	// 获取用户列表
	static Map getUserList(String nextOpenid = null){
		doGet('user/get', nextOpenid ? [next_openid: nextOpenid] : null)


//		return {"total":2,"count":2,"data":{"openid":["","OPENID1","OPENID2"]},"next_openid":"NEXT_OPENID"}
	}

	// 移动用户分组
	static Map updateUserGroup(String openid, int groupId){
		doPost('groups/members/update', [openid: openid, to_groupid: groupId])

		// return errcode/errmsg
	}

	// 批量移动用户分组
	static Map updateUserGroupBatch(List openidList, int groupId){
		doPost('groups/members/batchupdate', [openid_list: openidList, to_groupid: groupId])

		// return errcode/errmsg
	}

	// 用户备注修改
	static Map updateUserRemark(String openid, String remark){
		doPost('user/info/updateremark', [openid: openid, remark: remark])

		// return errcode/errmsg
	}

	// 获取用户信息，这个accessToken是oauth2登录确认后返回然后再调用接口获取的
	static Map getUserInfo4Auth(String accessToken, String openid){
		String url = urlApiHost + "sns/userinfo?access_token=${accessToken}&openid=${openid}"
		def objResult = JSON.parseObject(new URL(url).text)

		log.info('get user - ' + objResult)

		objResult
	}

	// 获取用户信息
	static Map getUserInfo(String openid){
		doGet('user/info', [openid: openid, lang: 'zh_CN'])
	}

	// 生成带参数的二维码
	// 用户扫描后，公众号可以接收到事件推送，event && eventKey == qrscene_${sceneStr}
	static Map getQrTicket(String sceneStr){
		def params = [:]
		// 临时的
		params.expire_seconds = 1800

		params.action_name = 'QR_LIMIT_STR_SCENE'
		params.action_info = [scene: [scene_str: sceneStr]]

		doPost('qrcode/create', params)

		// 图片展示url 
		// https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=**.ticket
	}

	// 长url转短url
	static Map long2shortUrl(String longUrl){
		doPost('shorturl', [action: 'long2short', long_url: longUrl])
	}

	// pic
	static byte[] downloadPic(String serverId){
		String accessToken = WxSignature.getAccessToken()
		String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=${accessToken}&media_id=${serverId}"

		try{
			return HttpRequest.get(url).bytes()
		}catch(e){
			log.error('download pic error', e)
			return null
		}
	}
}